package com.example.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/", configurator = WebSocketConfig.class)
@Slf4j
public class WebSocketServer {

    private static CopyOnWriteArraySet<MySocketRequest> sessionSet = new CopyOnWriteArraySet<MySocketRequest>();


    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        log.info("打开了连接：{}", session.getId());
        Map<String, Object> userProperties = config.getUserProperties();
        HandshakeRequest handshakeRequest = (HandshakeRequest) userProperties.get("HandshakeRequest");

        MySocketRequest request = new MySocketRequest();
        if (null != handshakeRequest) {
            request.setHttpSession((HttpSession) handshakeRequest.getHttpSession());
            log.info("客户端ip：{}", handshakeRequest.getRequestURI().getHost());
        }

        request.setSession(session);
        sessionSet.add(request);
    }

    @OnMessage
    public void OnMessage(Session session, String message) {

        log.info("收到消息：{}，{}", session.getId(), message);

    }


    @OnClose
    public void OnClose(Session session) {
        sessionSet.removeIf(obj ->
                obj.getSession().getId() == session.getId()
        );
        log.info("断开了连接：{}", session.getId());

    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误:{}，{}", session.getId(), error.getMessage());
        error.printStackTrace();
    }


    public void send(String s) throws IOException {

        Iterator<MySocketRequest> iterator = sessionSet.iterator();
        while (iterator.hasNext()) {
            Session session = iterator.next().getSession();
            session.getBasicRemote().sendText(s);
        }

    }
}
